<?php

namespace App\Listeners;

use Illuminate\Support\Facades\DB;
use Laravel\Passport\Events\RefreshTokenCreated;
use Laravel\Passport\Token;

class RevokeRefreshTokens {

	protected $token;
	/**
	 * Create the event listener.
	 *
	 * @return void
	 */
	public function __construct(Token $token) {
		$this->token = $token;
	}

	/**
	 * Handle the event.
	 *
	 * @param  object  $event
	 * @return void
	 */
	public function handle(RefreshTokenCreated $event) {
		$access_token = $this->token->find($event->accessTokenId);
		if (!$access_token) {
			return true;
		}
		$refresh_tokens = $this->token->where('user_id', $access_token->user_id)->select('id')->get();
		if (!$refresh_tokens) {
			return true;
		}
		$result = DB::table('oauth_refresh_tokens')->whereIn('access_token_id', array_column($refresh_tokens->toArray(), 'id'))->where('id', '<>', $event->refreshTokenId)->delete();
	}
}
